import {ConfigKey} from "../../../script/constant/ConfigConstant";
import Configer from "../../../script/frame/apiModel/config/Configer";
import {PlayerModel} from "../../../script/frame/apiModel/adapterModel/model4/PlayerModel";
import * as React from "../../../script/frame/apiModel/gui/React";
import {IProps, SyncId, UISyncData, View} from "../../../script/frame/apiModel/gui/React";
import {GuiId, GuiKeys} from "../../../script/controller/model/ControllerOpt";
import {BagInfo, GoodsBarInterface, ItemInfo} from "../../interface/GuiInterface";
import {ResourceKey} from "../../../script/constant/ResourceConstant";
import {PlayerFactory} from "../../../script/frame/PlayerFactory";
import {LightButton} from "../component/LightButton";
import GoodsBarContextMenu from "./GoodsBarContextMenu";
import {publicGui} from "../../interface/PublicGui";
import {InfoPageType} from "../common/InfoPage";
import {DataRouterUtil} from "../../../script/utils/router/DataRouterUtil";
import {DataRouter} from "../../../script/frame/dataSource/DataRouter";
import {CodeUtil} from "../../../script/frame/codeAdapter/CodeUtil";
import UnitUtil from "../../../script/utils/UnitUtil";
import {ColorStr, CombinationUIInfo} from "../../../script/type/Type";
import {TextAlign} from "../../../script/frame/apiModel/adapter/adapterInterface/model1/IFrameAdapter";

export interface IProp {
    getBags: (player: PlayerModel) => BagInfo;
    getCombinationInfoFun: (player: PlayerModel, itemId: string) => CombinationUIInfo;
}
export interface IState {
    goodsBags: ItemInfo[];
    equipItems: ItemInfo[];
    lv: number;

    contextIndex: number;
    contextX: number;
    contextY: number;
}

export default class GoodsBar extends GoodsBarInterface<IProp, IState> {
    oldGoodIndex: number = -1;


    constructor(props: IProp & IProps) {
        super(props);

        const goodsBags = [];
        const maxGoodsBagNum: number = Configer.getConfig(ConfigKey.maxGoodsBagNum);
        for (let i = 0; i < maxGoodsBagNum; i ++) {
            goodsBags.push({});
        }

        const equipItems = [];
        const maxGoodsEquipNum: number = Configer.getConfig(ConfigKey.maxGoodsEquipNum);
        for (let i = 0; i < maxGoodsEquipNum; i ++) {
            equipItems.push({});
        }

        this.state = {
            visible: false,
            lv: 0,
            goodsBags: goodsBags,
            equipItems: equipItems,
            contextX: -1,
            contextY: -1,
            contextIndex: -1,
        }
    }

    render = () => {
        const backSize = { h: 0.6, w: 0.26 };

        let XSpace: number = 0.01;
        let YSpace: number = 0.02;
        const iconSize = { h: 0.05, w: 0.03 }
        const backPos = { x: 0.61, y: 0.15 }

        const goodsBarPath = Configer.getResource(ResourceKey.goodsBarPath);
        const goodsVoidPath = Configer.getResource(ResourceKey.goodsVoidPath);
        const goodsTidyUpPath = Configer.getResource(ResourceKey.goodsTidyUpPath);
        const goldCloseButton = Configer.getResource(ResourceKey.goldCloseButton);
        const disableBlp = Configer.getResource(ResourceKey.disableBlp);

        const backPadding = { l: 0.025, t: 0.07 };

        const buttonSize = { w: 0.08, h: 0.04 };

        const closeButtonSize = { w: 0.02, h: 0.03 };
        const buttonMargin = backSize.w / 2 - buttonSize.w / 2  - backPadding.l;

        const item = this.state.contextIndex >= 0 ? this.state.goodsBags[this.state.contextIndex] : null;

        // if (item) {
        //     Logger.toastError('index' + this.state.contextIndex + 'this.state.goodsBags' + this.state.goodsBags.length)
        //     Logger.toastError(item.name)
        //     Logger.toastError(item.template.position + '')
        // }

        const labelSize = { h: 0.02, w: 0.03 }

        return <View   key={GuiKeys.goodsBarCon} style={{ hidden: !this.state.visible, backgroundImage: goodsBarPath, width: backSize.w, height: backSize.h, left: backPos.x, top: backPos.y, paddingT: backPadding.t, paddingL: backPadding.l }}>
            {
                this.state.goodsBags.map(
                    (itemModel: ItemInfo, index, array) => {
                        let backgroundImage = goodsVoidPath;
                        if (!CodeUtil.isNullOrZero(itemModel?.strId)) {
                            const itemData = DataRouter.getItemDataByItemId(itemModel.strId);
                            backgroundImage = DataRouterUtil.getIconUrlByIconData(itemData);
                        }
                        return <View   key={`${GuiKeys.goodsBarItem}|${index}`} onMouseDown={(event) => { return this.openContextMenu(event.x + iconSize.w, event.y - iconSize.h / 2, index) }} onMouseEnter={(event) => { this.openInfoPage(event.x, event.y, index) }} onMouseLeave={this.closeInfoPage} style={{ backgroundImage, marginT: YSpace, marginL: XSpace, width: iconSize.w, height: iconSize.h }}>
                            <View  key={`${GuiKeys.goodsBarItemNum}|${index}`} style={{ hidden: CodeUtil.isNullOrZero(itemModel?.num), backgroundImage: disableBlp, width: labelSize.w, height: labelSize.h, marginT: 0.03, fontSize: 0.02, fontAlign:TextAlign.center }}>{itemModel.num}</View>
                        </View>
                    }
                )
            }
            <LightButton key={GuiKeys.goodsBarButton} onMouseDown={ this.tidyUpItems } style={{ width: buttonSize.w, height: buttonSize.h, backgroundImage: goodsTidyUpPath, float: true, marginT: 0.43, marginL: buttonMargin }}></LightButton>
            <LightButton key={GuiKeys.goodsBarCloseButton} onMouseDown={this.clickClose} style={{ width: closeButtonSize.w, height: closeButtonSize.h, backgroundImage: goldCloseButton, float: true, marginT: -0.03, marginL: 0.195 }}></LightButton>
            <GoodsBarContextMenu key={GuiKeys.goodsBarContextMenuCon} clearCallBack={this.clearContextMenu} goodIndex={this.state.contextIndex} x={this.state.contextX} y={this.state.contextY} item={item}></GoodsBarContextMenu>
        </View>
    }

    tidyUpItems = () => {
        const syncData: UISyncData = { id: SyncId.tidyUpItems, param: { } };
        return syncData;
    }

    openContextMenu = (x: number, y: number, index: number) => {
        if (index === this.oldGoodIndex) {
            this.oldGoodIndex = -1
            this.setState({
                ...this.state,
                contextIndex: -1,
            })
        } else {
            this.oldGoodIndex = index;
            this.setState({
                ...this.state,

                contextX: x,
                contextY: y,
                contextIndex: index,
            })
        }
    }

    clearContextMenu = () => {
        this.oldGoodIndex = -1;
        this.setState({
            ...this.state,
            contextIndex: -1,
        })
    }

    close = () => {
        this.oldGoodIndex = -1;
        this.setState({
            ...this.state,
            visible: false,
            contextIndex: -1,
        })
    }

    openInfoPage = (x: number, y: number, index: number) => {
        const item = this.state.goodsBags[index];
        const template = DataRouter.getItemDataByItemId(item?.strId)
        const position = template?.position;

        if (template) {
            const combinationUIInfo = this.props.getCombinationInfoFun(PlayerFactory.getInstance().getLocalPlayer(), item?.strId);
            let { title: name, subTitle, des } = DataRouterUtil.getItemInfoDes(item, this.state.lv, combinationUIInfo);
            const fightValue = UnitUtil.getItemFightValue(template, item.affixs);
            const fightValueStr = CodeUtil.getColorStr(ColorStr.blue, '评分: ' + fightValue)
            subTitle = fightValueStr + '\n' + subTitle + '\n';
            publicGui.showInfoPage(x - 0.3, y, name, subTitle, des, InfoPageType.pos);
        } else {
            publicGui.closeInfoPage();
        }

        if (!CodeUtil.isNullOrZero(position)) {
            const targetItem = this.state.equipItems[position];
            const template = DataRouter.getItemDataByItemId(targetItem?.strId);

            if (template) {
                const combinationUIInfo = this.props.getCombinationInfoFun(PlayerFactory.getInstance().getLocalPlayer(), item?.strId);
                let { title: name, subTitle, des } = DataRouterUtil.getItemInfoDes(targetItem, this.state.lv, combinationUIInfo);
                name = name + CodeUtil.getColorStr(ColorStr.green, '(已装备)');
                const fightValue = UnitUtil.getItemFightValue(template, targetItem.affixs);
                const fightValueStr = CodeUtil.getColorStr(ColorStr.blue, '评分: ' + fightValue)
                subTitle = fightValueStr + '\n' + subTitle + '\n';
                publicGui.showInfoPage2(x - 0.6, y, name, subTitle, des, InfoPageType.pos);
            } else {
                publicGui.closeInfoPage2();
            }
        } else {
            publicGui.closeInfoPage2();
        }
    }

    closeInfoPage = () => {
        publicGui.closeInfoPage();
        publicGui.closeInfoPage2();
    }

    reflushGoodsBar = () => {
        const bags = this.props.getBags(PlayerFactory.getInstance().getLocalPlayer());

        const items = bags.bags;
        const equip = bags.equips;
        const lv = bags.lv;

        this.setState({
            ...this.state,
            visible: true,
            goodsBags: items,
            equipItems: equip,
            lv,
        });
    }

    clickClose = () => {
        const syncData: UISyncData = { id: SyncId.closeUI, param: { guiId: GuiId.goodsBar } };
        return syncData;
    }
}